package com.example.dao;
import com.example.bean.ActionBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("actionDaoImpl") //@Service为给类增加别名
public class ActionDaoImpl implements ActionDao {
    @Autowired //是用在JavaBean中的注解，通过byType形式，用来给指定的字段或方法注入所需的外部资源。
    private JdbcTemplate jdbcTemplate; //jdbc连接工具类

    // 查询指定 user_name 的所有 action_list
    // 假定数据库中该表名为 action
    @Override
    public List<ActionBean> findAllActionByUserName(String username) {
        String sql = "select * from action where username=?";
        Object[] params = new Object[]{username};
        return jdbcTemplate.query(
                sql,
                params,
                new BeanPropertyRowMapper<ActionBean>(ActionBean.class));
    }

    // 查询指定 user_name 指定 type 的所有 action_list
    @Override
    public List<ActionBean> findAllActionByUserNameAndType(String username, String type) {
        String sql = "select * from action where username=? and type=?";
        Object[] params = new Object[]{username, type};
        return jdbcTemplate.query(
                sql,
                params,
                new BeanPropertyRowMapper<ActionBean>(ActionBean.class));
    }

    @Override
    public boolean addAction(ActionBean action) {
        System.out.println(action.getUsername());
        System.out.println(action.getType());
        List<ActionBean> existedAction = this.findAllActionByUserNameAndType(action.getUsername(), action.getType());
        // 先查询username对应的userid
        String pre_sql = "select id from user where username=?";
        Object[] pre_params = new Object[]{action.getUsername()};
        List<Integer> pre_result = jdbcTemplate.queryForList(pre_sql, pre_params, Integer.class);
        if (pre_result.isEmpty()) {
            return false;
        }
        // 增
        if (existedAction.isEmpty()) {
            String sql = "insert into action(userid, username, type, set_up_time, action_list)values(?,?,?,?,?)";
            Object[] params = {pre_result.get(0) ,action.getUsername(), action.getType(), action.getSetUpTime(), action.getActionList()};
            return jdbcTemplate.update(sql, params)>0;
        } else { // 改
            String sql = "update action set set_up_time=?, action_list=? where username=? and type=?";
            Object[] params = {action.getSetUpTime(), action.getActionList(), action.getUsername(), action.getType()};
            return jdbcTemplate.update(sql, params)>0;
        }
    }

}
